package com.zz.hhbl.utils

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.content.ContextCompat.startActivity
import com.zz.framework.core.ext.alarmManager
import com.zz.framework.core.utils.AppGlobals
import com.zz.hhbl.App
import com.zz.hhbl.receiver.AlarmReceiver
import com.zz.hhbl.receiver.VersionUpdateAlarmReceiver
import java.util.Calendar

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/3/13 11:22.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
object LocationAlarmManager {

    fun startUpdateAlarm(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val alarmManager = AppGlobals.getApplication().alarmManager
            if (alarmManager?.canScheduleExactAlarms()!=true) {
                // 没有权限，引导用户到设置页面开启权限
                val intent = Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM)
                intent.data = Uri.parse("package:${AppGlobals.getApplication().packageName}")
                AppGlobals.getApplication().startActivity(intent)
            }else{
                setDailyAlarm()
            }
        }else{
            setDailyAlarm()
        }
    }

    private fun setDailyAlarm() {
        val alarmManager = AppGlobals.getApplication().alarmManager
        val intent = Intent(AppGlobals.getApplication(), VersionUpdateAlarmReceiver::class.java).apply {
            action = "ALARM_ACTION"
        }
        val pendingIntent = PendingIntent.getBroadcast(AppGlobals.getApplication(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
        // 计算触发时间（每天凌晨 1:00）
        val calendar = Calendar.getInstance().apply {
            timeInMillis = System.currentTimeMillis()
            set(Calendar.HOUR_OF_DAY, 1)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
        }
        // 如果设定时间已过，设定到第二天
        if (calendar.timeInMillis <= System.currentTimeMillis()) {
            calendar.add(Calendar.DAY_OF_YEAR, 1)
        }
        // 设置每日定时任务
        alarmManager?.setExactAndAllowWhileIdle(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            pendingIntent
        )
        Log.d("AlarmManager", "定时任务已设定，触发时间：${calendar.time}")
    }
}